<?php defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

/* JoomLeague League Management and Prediction Game for Joomla!
 * @version $Id: TipRanking.class.php 1163 2008-06-30 18:59:54Z jst $
 * @package Joomleague
 * @copyright Copyright (C) 2007  JoomLeague
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see _joomleague_license.txt
 *  
 * Homepage: http://www.joomleague.de
 * Support: htt://www.joomleague.de/forum/
 * 
 * This file is part of JoomLeague.
 *  
 * JoomLeague is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * Please note that the GPL states that any headers in files and
 * Copyright notices as well as credits in headers, source files
 * and output (screens, prints, etc.) can not be removed.
 * You can extend them with your own credits, though...
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
*/ 

class TipRanking{
  
  var $project;
  var $mode;

  // constructor and member initialisation
  function TipRanking(){
    $this->project = null;
    $this->mode = 0;
  }
  
  // sets the project
  function setProject(&$project){
    $this->project = $project;
  }

  // method getTippRanking provides the TipRanking information
  // for showUser and showTipRanking Dialogs
  // supported params are
  // mode:
  //   "1" : Ranking only for the one round from param2
  //   all : Ranking for alls round until the round in param2
  //   optimal: Ranking for optimal matchday (last matchday with min one match played)
  // round:
  //   parameter round for calculation (see param1)
  // roundbegin:
  //   parameter where ranking from
  // limit:
  //   parameter to set the side limit of the ranking
  // page:
  //   parameter to set the actual page
  // function:
  //   ''          : give the Ranking back
  //   'countUser' : give the count of tipuser back
  // filter_uid:
  //   parameter to filter the information of one specific user
  //   it's helpful for showUser Information charts, because here 
  //   all TipRankings of all rounds until $round have to be build
  //   and stored to RAM.
  //   So it save RAM, if only the user Ranking of the requested user is stored
  // show_all_user:
  //   parameter to show user without tipps
  
  function getTippRanking( $mode, $round, $roundbegin=1, $limit=0, $page=0, $function='', $filter_uid=0, $show_all_user=0 ) {
    $saisonEnde=0;
    $roundlist='';
    if($mode == 'all')  {
      $query = "SELECT COUNT(r.id)                  
                  FROM #__joomleague_rounds r 
                 WHERE r.project_id = ".$this->project->id;
      $this->project->_db->setQuery($query);
      $gesamtrounds = $this->project->_db->loadResult();
      
      $rounds = $this->project->getRounds($round, $roundbegin);
      $roundlist = implode(",",$rounds);
      
      if ($gesamtrounds==count($rounds)) $saisonEnde=1;
    } else {
      // try to get the optimal round
      // sysdate is used (MySQL 5.0.13, server offset is not implemented yet,
      // should be done soon)
      if ($mode == 'optimal') {
        $thistime=$this->project->getTimestamp('',1);
        $query = sprintf("SELECT max(matchcode)
                            FROM #__joomleague_matches m
                       LEFT JOIN #__joomleague_rounds r ON m.round_id = r.id
                           WHERE match_date <= '%s' AND match_date <> '0000-00-00 00:00:00' AND
                                 r.project_id = %s", date('Y-m-d H:i:s',$thistime), $this->project->id);
        $this->project->_db->setQuery($query);
        $round = $this->project->_db->loadResult();
      }
      
      $query = sprintf("SELECT id
                          FROM #__joomleague_rounds
                         WHERE matchcode = %s AND project_id = %s", $round,$this->project->id);
            
      $this->project->_db->setQuery($query);
      $rlist = $this->project->_db->loadResultArray();
      if ($rlist) $roundlist = implode(",",$rlist);
    }
    $table_config=$this->project->getTemplateConfig("show_tip_ranking.tpl");
    $res=0;
    $j=1;
    $order='';
    while ( array_key_exists( 'sort_order_'.$j,$table_config )) {
      switch ($table_config['sort_order_'.$j++]) {
        // 1. decision: more points
        case 'points':
          if ($order=='') $order='ORDER BY '; else $order.=', ';
          $order .= 'points DESC';
          break;
       
        case 'correct_tips':
          if ($order=='') $order='ORDER BY '; else $order.=', ';
          $order .= 'top DESC';
          break;
          
        case 'correct_diffs':
          if ($order=='') $order='ORDER BY '; else $order.=', ';
          $order .= 'diff DESC';
          break;
         
        case 'correct_tend':
          if ($order=='') $order='ORDER BY '; else $order.=', ';
          $order .= 'tend DESC';
          break;
          
        case 'count_tips_p':
          if ($order=='') $order='ORDER BY '; else $order.=', ';
          $order .= 'tipps DESC';
          break;
          
        case 'count_tips_m':
          if ($order=='') $order='ORDER BY '; else $order.=', ';
          $order .= 'tipps ASC';
          break;
          
        default;
          break;
      }
    }
    $results=array();
    $query = '';
    if ($filter_uid > 0) $query = " AND tr.user_id = $filter_uid";
    $query = sprintf("SELECT SUM(tp.point) AS points, SUM(tp.top) as top, SUM(tp.diff) as diff, SUM(tp.tend) as tend, count(tr.id) as tipps, SUM(tr.joker) as joker, tr.user_id
                        FROM #__joomleague_tip_results tr
                   LEFT JOIN #__joomleague_predictiongame_points tp ON tr.id=tp.tipp_id
                   LEFT JOIN #__joomleague_tip_members tm ON tm.user_id=tr.user_id and tm.project_id=tr.project_id
                   LEFT JOIN #__joomleague_matches m ON m.match_id = tr.match_id
                       WHERE tr.project_id=%s
                             AND tm.approved=1
                             AND m.round_id IN ($roundlist)".$query."
                       GROUP BY tr.user_id ".$order, $this->project->id);
    $this->project->_db->setQuery($query);
    $results = $this->project->_db->loadObjectList();
    $tipper_ranking = array();
    if ($results) foreach($results as $userid=>$uservar) {
      $tipper_ranking[$userid] = new TipMachine($this->project);
      $tipper_ranking[$userid]->points = $uservar->points;
      $tipper_ranking[$userid]->hitsCount = $uservar->top;
      $tipper_ranking[$userid]->diffCount = $uservar->diff;
      $tipper_ranking[$userid]->tendCount = $uservar->tend;
      $tipper_ranking[$userid]->tippCount = $uservar->tipps;
      $tipper_ranking[$userid]->joker = $uservar->joker;
      $tipper_ranking[$userid]->user_id = $uservar->user_id;
    }
    unset($results);
    
    if ($show_all_user) {
      $anzahltipper= (isset($tipper_ranking)) ? count($tipper_ranking) : 0;
      $query = sprintf("SELECT u.id as user_id, u.username
                          FROM #__users u
                          LEFT JOIN #__joomleague_tip_members tm ON u.id = tm.user_id
                         WHERE tm.approved = 1 AND tm.project_id = %s", $this->project->id);
      $this->project->_db->setQuery($query);
      $user = $this->project->_db->loadObjectList();
      foreach($user as $uservar) {
        $no_user=1;
        if (isset($tipper_ranking)) foreach($tipper_ranking as $key=>$val) {
          if($uservar->user_id==$val->user_id) {
            $no_user=0;
            break;
          }
        }
        if ($no_user==1) {
          $anzahltipper++;
          $tipper_ranking[$anzahltipper] = new TipMachine($this->project);
          $tipper_ranking[$anzahltipper]->setUserName($uservar->username);
          $tipper_ranking[$anzahltipper]->user_id = $uservar->user_id;
        }
      }
    }
    
    if ($function=='countUser') {
      return count($tipper_ranking);
    }
    $this->project->getPredictionConfig();
    if (($this->project->tip_champ==1) && ($mode=='all') && ($saisonEnde==1)) {
      $query = sprintf('SELECT COUNT(match_id)
                          FROM #__joomleague_matches 
                         WHERE (project_id=%s) AND (matchpart1_result is null and matchpart2_result is null) AND alt_decision=0',$this->project->id);
      $this->project->_db->setQuery($query);
      $offeneSpiele = $this->project->_db->loadResult();
      if ($offeneSpiele==0) {
        $show_table_config=$this->project->getTemplateConfig("show_table.tpl");
        $rankingliga = new Ranking();
        $rankingliga->setProjectConfig($this->project, $show_table_config['rankingorder']);
        $a = $rankingliga->getRanking(0, count($rounds), 1, $show_table_config['show_negative_points']);
        $merker = 0;
        foreach($a as $akey=>$aval){
          if ($merker==0) {
            $meister = $aval->team->teamtoolid;
            $merker = 1;
          }
        }
        foreach($tipper_ranking as $userid=>$uservar) {
          // get the champ tip, but convert the stored TTID to the teamId, which is used inside ranking
          $query = sprintf('SELECT tt.team_id
                              FROM #__joomleague_tip_members AS tu
                         LEFT JOIN #__joomleague_team_joomleague AS tt ON tt.id = tu.champ_tip
                            WHERE (tu.project_id=%s) AND tu.user_id=%s',$this->project->id, $uservar->user_id);
           $this->project->_db->setQuery($query);
          $champtip = $this->project->_db->loadResult();
          if ($champtip==$meister) {
            $tipper_ranking[$userid]->points += $this->project->tip_points_tip_champ;
          }
        }
        $tipptemp = new TipMachine($this->project);
        uasort($tipper_ranking, array ("TipMachine", "compare"));
        $rank=1;
        $previous_tipper = null;
        foreach($tipper_ranking as $key=>$val) {
          if ( ($previous_tipper != null) and ($val->compare($previous_tipper, $val)==0) ) {
            $tipper_ranking[$key]->rank = $previous_tipper->rank;
          } else {
            $tipper_ranking[$key]->rank = $rank;
          }
          $rank++;
          $previous_tipper=$tipper_ranking[$key];
        }
      }
    }
    $rank = 1;
    $previous_tipper = null;
    $showTipper=array();
    if (isset($tipper_ranking)) foreach($tipper_ranking as $tippranking) {
      if ( ($previous_tipper != null) and ($tippranking->compare($previous_tipper, $tippranking)==0) ) {
        $tippranking->rank = $previous_tipper->rank;
      } else {
        $tippranking->rank = $rank;
      }
      if (($rank>($page*$limit) && $rank<=(($page*$limit)+$limit)) || ($limit==0)) {
        $query = sprintf("SELECT u.username
                          FROM #__users u
                         WHERE u.id = %s", $tippranking->user_id);
        $this->project->_db->setQuery($query);
        $tippranking->username = $this->project->_db->loadResult();
        $showTipper[] = $tippranking;
      }
      $rank++;
      $previous_tipper=$tippranking;
      if (($rank>(($page*$limit)+$limit)) && $limit>0) break;
    }
    unset($tipper_ranking);
    return $showTipper;
  }
}  

?>
